package com.ihome.android.market2.frag;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ihome.android.EAFragment;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.CategoryID;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetViewAppDetailTask;
import com.ihome.android.market2.asynctask.SearchAppTask;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.SearchAppItem;
import com.ihome.android.market2.view.PageLine;
import com.ihome.android.util.CustomKeyboard;
import com.ihome.android.util.log.LogUtil;

public class SearchAppFragment extends EAFragment implements OnItemClickListener, OnClickListener, OnKeyListener {
	private final String	TAG								= SearchAppFragment.class.getSimpleName();
	private View			fragview;
	private int				mLocalCatg						= -1;
	private String			mLocalCatgName					= "";
	private ItemAdapter		mAdapter;
	private List<AppInfo>	mListApp;
	@EAInjectView(id = R.id.ll_search_tip)
	private LinearLayout	ll_search_tip;
	@EAInjectView(id = R.id.search_help_1)
	private TextView		search_help_1;
	@EAInjectView(id = R.id.search_help_2)
	private TextView		search_help_2;
	@EAInjectView(id = R.id.search_help_3)
	private TextView		search_help_3;
	@EAInjectView(id = R.id.ll_search_noresult)
	private LinearLayout	ll_search_noresult;
	@EAInjectView(id = R.id.gv_search_app)
	private RelativeLayout	mSearchApp;
	@EAInjectView(id = R.id.search_pageline)
	private PageLine		mPageLine;
	@EAInjectView(id = R.id.gv_category_app)
	private GridView		mGridView;
	@EAInjectView(id = R.id.tv_page_pre)
	private TextView		tv_page_pre;
	@EAInjectView(id = R.id.tv_page_next)
	private TextView		tv_page_next;
	@EAInjectView(id = R.id.category_line)
	private RelativeLayout	category_line;
	@EAInjectView(id = R.id.edt_searchkey)
	private EditText		edt_searchkey;
	@EAInjectView(id = R.id.glKeys)
	private GridLayout		glKeys;
	private CustomKeyboard	mCustomKeyboard					= null;

	/** 该分类当前页数 */
	private int				mCurPage						= 1;
	/** 该分类APP总数 */
	private int				mAppNum							= 0;
	/** 每页展示的APP数量 */
	private final int		APPNUM_PER_PAGE					= 6;

	private final int		MSG_SPINEER_APP_LIST_REFRESH	= 3;
	private final int		MSG_SHOW_PREVIEW_PAGE			= 6;
	private final int		MSG_SHOW_NEXT_PAGE				= 8;
	private final int		MSG_KEYBOARD_INPUT				= 10;
	private final int		MSG_FOCUS_SEARCHRESULT			= 11;
	private final int		MSG_REFOCUS_SEARCHRESULT		= 13;
	private final int		MSG_NOFOCUS_SEARCHRESULT		= 12;
	private final String	INPUT_RESULT					= "input_result";
	private Handler			mHandler;

	private ImageLoader		imageLoader;
	public static boolean	firstEnter						= true;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SPINEER_APP_LIST_REFRESH:
					mCurPage = 1;
					getCategoryList();
					break;
				case MSG_SHOW_NEXT_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_NEXT_PAGE ------");
					if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
						mCurPage++;
						if ((mCurPage * APPNUM_PER_PAGE) > mListApp.size() && mListApp.size() < mAppNum) {
							getCategoryList();
						}
						else {
							mAdapter.notifyDataSetChanged();
							setPageLine();
						}
						
					}
					break;
				case MSG_SHOW_PREVIEW_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_PREVIEW_PAGE ------");
					if (mCurPage > 1) {
						mCurPage--;
						mAdapter.notifyDataSetChanged();
						setPageLine();
					}
					break;
				case MSG_KEYBOARD_INPUT:
					edt_searchkey.setText(msg.getData().getString(INPUT_RESULT));
					clearSearchResult();
					if (msg.getData().getString(INPUT_RESULT).trim() != "") {
						doSearch();
					}
					else {
						mCustomKeyboard.requestFocus(false);
						ll_search_noresult.setVisibility(View.GONE);
						mSearchApp.setVisibility(View.GONE);
						ll_search_tip.setVisibility(View.VISIBLE);
					}
					break;
				case MSG_FOCUS_SEARCHRESULT:
					if (mAdapter != null) {
						LogUtil.e(TAG, "====== MSG_FOCUS_SEARCHRESULT is set====");
						
						if(mAdapter.getItemFocusable() == false){
							mAdapter.setItemFocusable(true);
							mAdapter.notifyDataSetChanged();
						}
					}
					break;
				case MSG_NOFOCUS_SEARCHRESULT:
					if (mAdapter != null) {
						mAdapter.setItemFocusable(false);
						mAdapter.notifyDataSetChanged();
					}
					break;
				case MSG_REFOCUS_SEARCHRESULT:
					if (mAdapter != null) {
						mAdapter.setItemFocusable(true);
						mAdapter.notifyDataSetChanged();
						mAdapter.requestFocus();
					}
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		LogUtil.i(TAG, "--> onAttach");

		mLocalCatg = getArguments().getInt(HttpKeys.KEY_CID, -1);
		mLocalCatgName = getArguments().getString(HttpKeys.KEY_CIDNAME);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		procHandler();

		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.icon_default);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, " -->  onCreateView()");
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_search_app, container, false);

		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() ");
	}

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		LogUtil.i(TAG, " -->  setArguments()");
	}

	public void initData() {
		if (mListApp == null || mListApp.size() == 0) {
			getCategoryList();
		}
		else {
			focusView();
		}
	}

	public void focusView() {
		if (mLocalCatg != -1 && mLocalCatg == CategoryID.CATEGORY_SEARCH) {
		}
	}

	public boolean isFocusAtCategoryLine() {
		return !mGridView.hasFocus();
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");

		if (mLocalCatg != -1 && mLocalCatg == CategoryID.CATEGORY_SEARCH) {
			edt_searchkey.setText("");//clear text content
			search_help_1.setText(Html.fromHtml(getString(R.string.search_help_1)));
			search_help_2.setText(Html.fromHtml(getString(R.string.search_help_2)));
			search_help_3.setText(Html.fromHtml(getString(R.string.search_help_3)));
			showKeyboard();
		}

		mAdapter = new ItemAdapter(getActivity());
		mGridView.setAdapter(mAdapter);
		mGridView.setFocusable(false);
		mGridView.setOnItemClickListener(this);
		mGridView.setOnKeyListener(this);
		tv_page_pre.setOnClickListener(this);
		tv_page_next.setOnClickListener(this);
		edt_searchkey.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {}
		});

		initData();
	}

	/**
	 * 设置页数和APP总数
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void setPageLine() {
		mPageLine.setVisibility(View.VISIBLE);
		mPageLine.setPageNum(mCurPage, mAppNum, APPNUM_PER_PAGE, false);

		if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
			tv_page_next.setVisibility(View.VISIBLE);
		}

		if (mCurPage * APPNUM_PER_PAGE >= mAppNum) {
			tv_page_next.setVisibility(View.GONE);
			mGridView.requestFocus();
		}

		if (mCurPage == 1) {
			mGridView.requestFocus();
			tv_page_pre.setVisibility(View.GONE);
		}

		if (mCurPage > 1) {
			tv_page_pre.setVisibility(View.VISIBLE);
		}
	}

	private void getCategoryList() {
		LogUtil.i(TAG, " -->  getCategoryList() mLocalCatg = " + mLocalCatg);
		if (mLocalCatg == CategoryID.CATEGORY_SEARCH) {
			doSearch();
			return;
		}
	}

	public void doSearch() {
		String keyword = edt_searchkey.getText().toString().trim();
		LogUtil.d(TAG, "--------keyword ==== " + keyword);

		if (keyword == null || keyword.length() == 0) {
			//			edt_searchkey.requestFocus();
			return;
		}

		Bundle b = new Bundle();
		b.putInt(HttpKeys.KEY_STARTINDEX, (mCurPage - 1) * APPNUM_PER_PAGE);
		b.putInt(HttpKeys.KEY_SORT, 0);
		b.putInt(HttpKeys.KEY_CHARGE, 0);
		b.putInt(HttpKeys.KEY_MAXNUM, APPNUM_PER_PAGE);
		b.putString(HttpKeys.KEY_KEYWORD, keyword);
		b.putString(HttpKeys.KEY_PACKAGENAME, "");
		new SearchAppTask(getActivity(), SearchAppFragment.this).execute(b);
	}

	class ItemAdapter extends BaseAdapter {
		private LayoutInflater	mInflater;
		private Context			context;
		private View			view;
		private boolean			itemFocusable	= false;

		public ItemAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;

		}

		@Override
		public int getCount() {
			int i = 0;
			if (mListApp != null && mListApp.size() > 0) {
				if (mListApp.size() > APPNUM_PER_PAGE * mCurPage) {
					i = APPNUM_PER_PAGE;
				}
				else {
					i = mListApp.size() - APPNUM_PER_PAGE * (mCurPage - 1);
				}
			}

			if (i < 0)
				i = 0;

			if (i > APPNUM_PER_PAGE)
				i = APPNUM_PER_PAGE;

			return i;
		}

		@Override
		public Object getItem(int position) {
			if (mListApp == null)
				return null;

			int index = APPNUM_PER_PAGE * (mCurPage - 1) + position;
			if (mListApp.size() <= index)
				return null;

			return mListApp.get(index);
		}

		@Override
		public long getItemId(int position) {
			return position;
		};

		public void requestFocus() {
			if (view != null) {
				view.requestFocus();
			}
			else {
				LogUtil.e(TAG, "requestFocus() view is NULL ");
			}
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			SearchAppItem appItem;

			final AppInfo appInfo = (AppInfo) getItem(position);

			if (null == convertView) {
				appItem = new SearchAppItem(context, imageLoader);
				convertView = appItem.getView();
				convertView.setTag(appItem);
			}
			else {
				appItem = (SearchAppItem) convertView.getTag();
			}

			appItem.setFocusable(itemFocusable);
			appItem.initView(appInfo);
			appItem.setOnKeyListener(SearchAppFragment.this);

			appItem.setClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Bundle b = new Bundle();
					b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(appInfo.getAppId()));
					b.putString(HttpKeys.KEY_PATHID, "");
					new GetViewAppDetailTask(SearchAppFragment.this.getActivity(),
							SearchAppFragment.this,Integer.parseInt(appInfo.getAppId())).execute(b);
				}
			});

			if (position == 0) {
				view = convertView;
			}

			return convertView;
		}

		public void setItemFocusable(boolean focusable) {
			itemFocusable = focusable;
		}
		
		public boolean getItemFocusable() {
			return itemFocusable;
		}
	}

	/**
	 * 成功获取应用列表回调方法
	 * 
	 * @param mAppList
	 * @param appsNum
	 */
	public void getAppSuccess(List<AppInfo> mAppList, int appsNum) {
		LogUtil.d(TAG, "--------getAppSuccess ==== ");

		mAppNum = appsNum;
		mListApp = mAppList;
		mAdapter.setItemFocusable(false);
		mAdapter.notifyDataSetChanged();
		focusView();
		setPageLine();

		ll_search_tip.setVisibility(View.GONE);
		if (mListApp.size() > 0) {
			ll_search_noresult.setVisibility(View.GONE);
			mSearchApp.setVisibility(View.VISIBLE);
		}
		else if (mListApp.size() == 0) {
			mSearchApp.setVisibility(View.INVISIBLE);
			ll_search_noresult.setVisibility(View.VISIBLE);
		}
		if(mCustomKeyboard.requestFocus(false) == true){
			mHandler.sendEmptyMessage(MSG_FOCUS_SEARCHRESULT);
		}
		
	}

	public void addApps(List<AppInfo> mAppList) {
		mListApp.addAll(mAppList);
		mAdapter.setItemFocusable(true);
		mAdapter.notifyDataSetChanged();
		focusView();
		setPageLine();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		AppInfo info = (AppInfo) arg0.getItemAtPosition(arg2);
		
		Bundle b = new Bundle();
		b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(info.getAppId()));
		b.putString(HttpKeys.KEY_PATHID, "");
		new GetViewAppDetailTask(SearchAppFragment.this.getActivity(),
				SearchAppFragment.this,Integer.parseInt(info.getAppId())).execute(b);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_page_pre:
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			break;
		case R.id.tv_page_next:
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		LogUtil.v(TAG, " --> onKey() keyCode = " + keyCode);

		if (keyCode == 92 && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			return true;
		}
		else if (keyCode == 93 && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			return true;
		}
		return false;
	}

	public void showKeyboard() {
		if (mCustomKeyboard == null) {
			mCustomKeyboard = new CustomKeyboard(getActivity(), mHandler, glKeys, fragview);
		}
		mCustomKeyboard.initView();
		mCurPage = 1;
		if (mGridView != null) {
			mAppNum = 0;
			if (mListApp != null) {
				mListApp.clear();
			}
			if (mAdapter != null) {
				mAdapter.notifyDataSetChanged();
			}
		}
		mCustomKeyboard.requestFocus(true);
	}

	private void clearSearchResult() {
		if (mGridView != null) {
			mAppNum = 0;
			mCurPage = 1;
			if (mListApp != null) {
				mListApp.clear();
			}
			if (mAdapter != null) {
				mAdapter.notifyDataSetChanged();
			}
			setPageLine();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		firstEnter = true;
	}

	private void releaseFocus() {
		mGridView.setFocusable(false);
		mGridView.clearFocus();
	}
	

	public void toDetailPage(int appId){
		Intent intent = new Intent();
		intent.putExtra(HttpKeys.KEY_APPID, appId);
		intent.setClass(getActivity(), DetailActivity.class);
		getActivity().startActivity(intent);
	}
}
